/*
 * Author: JacksonCoder
 * FileName: ThreadPoolTimeoutExample
 * Version: 1.0.0
 * Date: 2025/2/24
 */

import java.util.concurrent.*;

public class ThreadPoolTimeoutExample {

    public static void main(String[] args) {
        // 创建一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 创建一个Callable任务
        Callable<String> task = () -> {
            // 模拟执行10秒的任务
            Thread.sleep(10000);
            return "Task completed";
        };

        // 提交任务并获取Future对象
        Future<String> future = executor.submit(task);

        try {
            // 设置任务的超时时间为1秒
            String result = future.get(1, TimeUnit.SECONDS); // 1秒超时
            System.out.println(result);
        } catch (TimeoutException e) {
            System.out.println("Task timed out");
            future.cancel(true); // 取消任务
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }

    }

}
